<template>
  <el-dialog
    :visible.sync="visible"
    :append-to-body="true"
    :close-on-click-modal="false"
    :before-close="handleClose"
    :title="tit + '查重'"
    custom-class="no-padding-dialog"
    width="800px"
  >
    <div
      v-loading="loading"
      :class="{ 'show-table': showTable }"
      class="duplicate-check"
    >
      <div class="d-flex justify-content-between align-items-end">
        <div style="width:140px;">
          <span class="title">
            {{ tit == "线索" ? "客户姓名" : tit + "名称" }}
          </span>
          <el-input
            v-model="searchContent.name"
            class="search-input"
            clearable
            @keyup.enter.native="getList"
            :placeholder="
              tit == '线索' ? '请输入客户姓名' : '请输入' + tit + '名称'
            "
          ></el-input>
        </div>
        <div>
          <span class="title">
            手机号/电话
          </span>
          <el-input
            v-model="searchContent.phone"
            class="search-input"
            @keyup.enter.native="getList"
            :placeholder="'请输入手机号/电话'"
            clearable
          ></el-input>
        </div>
        <div>
          <span class="title">
            微信号
          </span>
          <el-input
            v-model="searchContent.wechat"
            class="search-input"
            @keyup.enter.native="getList"
            :placeholder="'请输入微信号'"
            clearable
          ></el-input>
        </div>
        <el-button type="primary" @click.native="getList">查重</el-button>
        <!-- <el-input
          v-model="searchContent"
          class="search-input"
          @keyup.enter.native="getList"
        >
          <el-select slot="prepend" v-model="typeSelect">
            <el-option
              :label="tit == '线索' ? '按微信昵称' : '按' + tit + '名称'"
              value="name"
            />
            <el-option label="按手机号/电话" value="phone" />
            <el-option label="按微信" value="wechat" />
          </el-select>
          <el-button slot="append" type="primary" @click.native="getList"
            >查重</el-button
          >
        </el-input> -->
      </div>

      <el-table
        v-if="showTable"
        :data="tableData"
        :cell-class-name="cellClassName"
        class="duplicate-check__content"
        border
        height="380"
        style="width: 100%"
        @row-click="handleRowClick"
      >
        <el-table-column
          v-for="(item, index) in fieldList"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          :min-width="item.width"
          show-overflow-tooltip
          :formatter="fieldFormatter"
        />
        </el-table-column>
      </el-table>

      <div v-if="showTable" class="duplicate-check__footer">
        注：查重结果最多显示10条，如不完整，请完善查重条件
      </div>

      <c-r-m-full-screen-detail
        :visible.sync="showFullDetail"
        :crm-type="relationCrmType"
        :id="relationId"
        :pool-id="poolId"
        @handle="getList"
      />

      <alloc-handle
        :pool-id="poolId"
        :selection-list="[relationData]"
        :dialog-visible.sync="allocDialogShow"
        crm-type="customer"
        @handle="getList"
      />
    </div>
  </el-dialog>
</template>

<script>
import {
  crmCustomerReceiveAPI,
  crmCustomerDataCheckAPI,
} from "@/api/crm/customer";
import { crmLeadsDataCheckAPI } from "@/api/crm/leads";
import AllocHandle from "../SelectionHandle/AllocHandle"; // 公海分配操作

import crmTypeModel from "@/views/crm/model/crmTypeModel";

export default {
  name: "DuplicateCheck",
  components: {
    AllocHandle,
    CRMFullScreenDetail: () => import("@/components/CRMFullScreenDetail"),
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    tit: {
      type: String,
      default: "",
    },
    crmType: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      loading: false,
      typeSelect: "name",
      searchContent: {
        name: "",
        wechat: "",
        phone: "",
      },
      tableData: null,

      showFullDetail: false, // 查看相关学员管理详情
      relationId: "", // 相关ID参数
      relationData: {}, // 关联数据
      poolId: "", // 公海Id
      relationCrmType: "", // 相关类型
      allocDialogShow: false, //  分配弹窗
    };
  },
  computed: {
    showTable() {
      return this.tableData;
    },

    isCustomerFilter() {
      return this.typeSelect == "name";
    },

    // 学员名称、创建时间、负责人、最后跟进时间、操作
    fieldList() {
      if (this.isCustomerFilter) {
        return [
          {
            prop: "name",
            label: this.tit == "线索" ? "客户姓名" : "学员名称",
            width: 160,
          },
          {
            prop: "telephone",
            label: "手机号",
            width: 100,
          },
          {
            prop: "wechat",
            label: "微信号",
            width: 100,
          },
          {
            prop: "ownerUserName",
            label: this.tit == "线索" ? "销售负责人" : "负责人",
            width: 100,
          },
          {
            prop: "createUserName",
            label: "创建人",
            width: 100,
          },
          {
            prop: "createTime",
            label: "创建时间",
            width: 160,
          },
        ];
      }

      return [
        {
          prop: "mobile",
          label: "手机号/电话",
          width: 160,
        },
        {
          prop: "contactsName",
          label: "联系人",
          width: 160,
        },
        {
          prop: "name",
          label: "学员名称",
          width: 200,
        },
        {
          prop: "ownerUserName",
          label: "负责人",
          width: 100,
        },
        {
          prop: "createUserName",
          label: "创建人",
          width: 100,
        },
        {
          prop: "createTime",
          label: "创建时间",
          width: 100,
        },
        {
          prop: "module",
          label: "模块",
          width: 100,
        },
      ];
    },
  },
  watch: {
    typeSelect() {
      // this.searchContent = "";
      this.tableData = null;
    },
  },
  mounted() {},
  methods: {
    handleClose() {
      this.$emit("update:visible", false);
      this.resetData();
    },

    resetData() {
      this.typeSelect = "name";
      this.searchContent = {
        name: "",
        wechat: "",
        phone: "",
      };
      this.tableData = null;
    },

    getList() {
      if (
        !this.searchContent.name &&
        !this.searchContent.phone &&
        !this.searchContent.wechat
      ) {
        return;
      }
      const params = {
        name: this.searchContent.name,
        wechat: this.searchContent.wechat,
        phone: this.searchContent.phone,
      };
      // params[this.typeSelect] = this.searchContent[this.typeSelect];
      this.loading = true;
      this.loading = false;
      let postUrl;
      if (this.crmType == "leads") {
        postUrl = crmLeadsDataCheckAPI;
      } else if (this.crmType == "customer") {
        postUrl = crmCustomerDataCheckAPI;
      }
      postUrl(params)
        .then((res) => {
          this.loading = false;
          const list = res.data || [];
          this.tableData = list.map((item) => {
            item.module = crmTypeModel.convertTypeToName(item.type);
            if (item.poolName) {
              item.module = `${item.module}（${item.poolName}）`;
            }
            // 是手机号
            if (!this.isCustomerFilter) {
              item.mobile = this.searchContent.phone;
              if (item.type == crmTypeModel.contacts) {
                item.contactsName = item.name;
                item.contactsId = item.id;

                item.name = item.customerName;
                item.id = item.customerId;
                // name 字段对应的点击类型 以type为准，所以将type校准为学员
                // 联系人详情 已 contactsId 为准
                item.type = crmTypeModel.customer;
              }
            }

            return item;
          });
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 列表点击
     */
    handleRowClick(row, column, event) {
      if (column.property == "name" && row.id) {
        this.relationId = row.id;
        if (row.poolAuthList) {
          this.poolId = row.poolAuthList.poolId;
        } else {
          this.poolId = "";
        }
        const key = crmTypeModel.convertTypeToKey(row.type);
        this.relationCrmType = key == "pool" ? "customer" : key;
        this.showFullDetail = true;
      } else if (column.property == "contactsName" && row.contactsId) {
        this.relationId = row.contactsId;
        this.relationCrmType = "contacts";
        this.showFullDetail = true;
      }
    },

    /**
     * 通过回调控制class
     */
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (column.property === "name" || column.property === "contactsName") {
        return "can-visit--underline";
      } else {
        return "";
      }
    },

    handleClick(type, data) {
      if (type === "receive") {
        this.$confirm("确定要领取该学员吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            crmCustomerReceiveAPI({
              ids: [data.id],
              poolId: data.poolAuthList.poolId,
            })
              .then((res) => {
                this.$message.success("操作成功");
                this.getList();
              })
              .catch(() => {});
          })
          .catch(() => {});
      } else {
        data["customerId"] = data.id;
        this.relationData = data;
        this.allocDialogShow = true;
      }
    },
    fieldFormatter(row, column, cellValue) {
      return !row[column.property] ? "--" : row[column.property];
    },
  },
};
</script>

<style scoped lang="scss">
.duplicate-check {
  position: relative;
  padding: 20px;
  padding-bottom: 40px;

  &__content {
    margin-top: 15px;
  }

  &__footer {
    margin-top: 10px;
    font-size: 12px;
    color: #666;
  }
  .search-input {
    margin-top: 10px;
  }

  .title {
    color: #333;
    font-size: 12px;
  }

  button {
    height: 34px;
  }
}

.duplicate-check.show-table {
  padding-bottom: 20px;
}

.el-input {
  /deep/ .el-select .el-input {
    width: 130px;
    /deep/ i {
      font-weight: bold;
    }
  }

  /deep/ .el-input-group__append {
    background-color: $xr-color-primary;
    border-color: $xr-color-primary;
    color: white;

    .el-button {
      /deep/ i {
        margin-right: 5px;
        font-size: 14px;
      }
    }
  }
}
</style>
